package com.geekbang.work6;

import org.apache.shardingsphere.driver.api.yaml.YamlShardingSphereDataSourceFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @author nhsoft.lul
 */
@SpringBootApplication
@MapperScan(basePackages = {"com.geekbang.work6.mapper"})
@RestController
public class AtomikosXaApplication{

    @Resource
    private BookOrderService bookOrderService;

    public static void main(final String args[]) {
        SpringApplication.run(AtomikosXaApplication.class, args);
    }

    @Bean
    public DataSource shardingDatasource() throws IOException, SQLException {
        String fileName = "config-sharding.yaml";
        File yamlFile = new File(AtomikosXaApplication.class.getClassLoader().getResource(fileName).getPath());
        return YamlShardingSphereDataSourceFactory.createDataSource(yamlFile);
    }


    @GetMapping("test")
    public void test(){
        bookOrderService.delete();
        bookOrderService.save();
    }

    @GetMapping("testRollback")
    public void testRollback(){
        bookOrderService.delete();
        bookOrderService.saveRollback();
    }

    @GetMapping("count")
    public Integer count(){
        return bookOrderService.list().size();
    }

    @GetMapping("delete")
    public void delete(){
        bookOrderService.delete();
    }
}
